<template>
  <div class="role-list">
    <!-- 搜索和操作区域 -->
    <div class="operation-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.name" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="operation-buttons">
        <el-button type="primary" @click="handleAdd">添加角色</el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="roleList"
      border
      style="width: 100%"
    >
      <el-table-column type="index" width="50" />
      <el-table-column prop="name" label="角色名称" width="150" />
      <el-table-column prop="description" label="角色描述" min-width="200" />
      <el-table-column label="权限数量" width="100">
        <template #default="{ row }">
          <el-tag>{{ row.permissionCount || 0 }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="primary" link @click="handlePermission(row)">分配权限</el-button>
          <el-button 
            type="danger" 
            link 
            @click="handleDelete(row)"
            :disabled="row.id === 1"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑角色' : '添加角色'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input 
            v-model="formData.name" 
            placeholder="请输入角色名称"
            :disabled="isEdit && formData.id === 1"
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限分配对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="分配权限"
      width="600px"
    >
      <el-tree
        ref="permissionTree"
        :data="permissionList"
        show-checkbox
        node-key="id"
        :props="{
          label: 'name',
          children: 'permissions'
        }"
        :default-checked-keys="selectedPermissions"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePermissionSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getRoleList, getPermissionList, getRolePermissions, updateRolePermissions } from '@/api/admin'

const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const isEdit = ref(false)
const roleList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const formRef = ref(null)
const permissionList = ref([])
const selectedPermissions = ref([])
const currentRole = ref(null)
const permissionTree = ref(null)

// 搜索表单
const searchForm = ref({
  name: ''
})

// 表单数据
const formData = ref({
  name: '',
  description: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 64, message: '长度在 2 到 64 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 255, message: '长度不能超过 255 个字符', trigger: 'blur' }
  ]
}

// 获取角色列表
const fetchRoleList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm.value
    }
    const res = await getRoleList(params)
    roleList.value = res || []
    total.value = res.length || 0
  } catch (error) {
    console.error('获取角色列表失败：', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 获取权限列表
const fetchPermissionList = async () => {
  try {
    const res = await getPermissionList()
    // 将权限数据转换为树形结构
    const permissionGroups = {
      '系统管理': ['system:config', 'role:manage', 'log:audit'],
      '用户管理': ['user:audit', 'user:manage'],
      '商铺管理': ['shop:audit', 'shop:monitor'],
      '内容管理': ['content:manage'],
      '订单管理': ['order:view', 'order:arbitrate'],
      '财务管理': ['financial:settlement']
    }

    const treeData = Object.entries(permissionGroups).map(([groupName, codes]) => ({
      name: groupName,
      permissions: res.filter(p => codes.includes(p.code))
    }))

    permissionList.value = treeData
  } catch (error) {
    console.error('获取权限列表失败：', error)
    ElMessage.error('获取权限列表失败')
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchRoleList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    name: ''
  }
  handleSearch()
}

// 添加角色
const handleAdd = () => {
  isEdit.value = false
  formData.value = {
    name: '',
    description: ''
  }
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = (row) => {
  isEdit.value = true
  formData.value = { ...row }
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true

    if (isEdit.value) {
      await updateRole(formData.value.id, formData.value)
      ElMessage.success('修改成功')
    } else {
      await createRole(formData.value)
      ElMessage.success('添加成功')
    }

    dialogVisible.value = false
    fetchRoleList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交失败：', error)
      ElMessage.error('提交失败，请检查表单')
    }
  } finally {
    submitting.value = false
  }
}

// 删除角色
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该角色吗？此操作不可恢复！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteRole(row.id)
    ElMessage.success('删除成功')
    fetchRoleList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除角色失败：', error)
      ElMessage.error('删除失败')
    }
  }
}

// 分配权限
const handlePermission = async (row) => {
  currentRole.value = row
  try {
    const res = await getRolePermissions(row.id)
    selectedPermissions.value = res.map(p => p.id) || []
    permissionDialogVisible.value = true
  } catch (error) {
    console.error('获取角色权限失败：', error)
    ElMessage.error('获取角色权限失败')
  }
}

// 提交权限分配
const handlePermissionSubmit = async () => {
  if (!currentRole.value) return
  
  try {
    submitting.value = true
    const checkedKeys = permissionTree.value.getCheckedKeys()
    const halfCheckedKeys = permissionTree.value.getHalfCheckedKeys()
    const permissionIds = [...checkedKeys, ...halfCheckedKeys]

    await updateRolePermissions(currentRole.value.id, permissionIds)
    ElMessage.success('权限分配成功')
    permissionDialogVisible.value = false
    fetchRoleList()
  } catch (error) {
    console.error('分配权限失败：', error)
    ElMessage.error('分配权限失败')
  } finally {
    submitting.value = false
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchRoleList()
}

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchRoleList()
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  fetchRoleList()
  fetchPermissionList()
})
</script>

<style lang="scss" scoped>
.role-list {
  .operation-area {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    .search-form {
      flex: 1;
    }

    .operation-buttons {
      margin-left: 20px;
    }
  }

  .pagination-area {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 